package com.example.bobo.yuejian322.Activity;


import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import android.os.Bundle;

import com.example.bobo.yuejian322.Fragment.LoginFragment;
import com.example.bobo.yuejian322.Fragment.MainFragment;
import com.example.bobo.yuejian322.R;
import com.example.bobo.yuejian322.base.BaseActivity;

public class MainActivity extends BaseActivity {

    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;
    private LoginFragment loginFragment;
    private MainFragment mainFragment;
    //简单数据存储。
    private SharedPreferences preferences;
    private  final String fileName="food";
    private   final int mode = MODE_PRIVATE;//权限

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        preferences = getSharedPreferences(fileName,mode);
        fragmentManager=getSupportFragmentManager();

        //判断状态
        boolean loginState=getLoginState();
        if(loginState){
            //进入主界面
            showMainFragment();
            //showLoginFragment();
        }else {
            //显示登录
            showLoginFragment();
           // showMainFragment();
        }




    }


    private  void showLoginFragment(){
        transaction=fragmentManager.beginTransaction();
        loginFragment=new LoginFragment();
        transaction.add(R.id.fragment_holder,loginFragment);

        transaction.commit();
    }

    private  void showMainFragment(){
        transaction=fragmentManager.beginTransaction();
        mainFragment=new MainFragment();
        transaction.add(R.id.fragment_holder,mainFragment);

        transaction.commit();

    }
    public void replaceLoginFragment(){
        mainFragment=new MainFragment();
        transaction=fragmentManager.beginTransaction();
        transaction.replace(R.id.fragment_holder,mainFragment);
        transaction.commit();

    }



    //判断是否登录，如果登录，进入主页面。否则，显示登录界面。
    private  boolean getLoginState() {

        userId= getSavedUserId();
        return ! userId.equals("-1");

    }
    //从本地文件读取ID
    private  String getSavedUserId(){

        String userId=preferences.getString("user_id","-1");
        return  userId;

    }

    //把id写入本地文件
    public   void setSavedUserId(String userId){

        SharedPreferences.Editor editor =preferences.edit();
        editor.putString("user_id",userId);
        editor.commit();

    }


}